package com.bocai.controller;


import com.bocai.bean.OrderInfo;
import com.bocai.bean.TCMObject;
import com.bocai.service.IOrderService;
import com.bocai.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("notification")
public class ReceiveNotificationController {

    @Autowired
    IOrderService orderService;

    @ApiOperation(value = "接收第三方API推送通知", notes = "接收第三方API推送通知")

    @RequestMapping(value = "/received", method = RequestMethod.POST)
    @ResponseBody
    public int received(HttpServletRequest request) {

        System.out.println("===============receiveNotificationBegin======================");

        JSONObject jsonObject = this.bodyFromRequest(request);
        String type = jsonObject.getString("type").trim();

        System.out.println("type:" + type);

        switch (type) {
            case "OrderChangedNotification":
                this.orderChangedNotificationHandle(jsonObject);
                System.out.println(jsonObject);
                break;
            case "EventChangedNotification":
                break;
            case "EventCasesChangedNotification":
                break;
            case "EventStatsChangedNotification":
                break;
            case "EventMarketsChangedNotification":
                this.marketChangedNotificationHandle(jsonObject);
                break;
            default:
        }

        System.out.println("===============receiveNotificationEnd======================");

        return 1;
    }

    @ApiOperation(value = "订阅比赛", notes = "订阅比赛")

    @RequestMapping(value = "subscribeEvent", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "countryId", dataType = "Integer", required = false, value = "国家id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "competitionId", dataType = "Integer", required = false, value = "赛事id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "beginTime", dataType = "Long", required = true, value = "比赛开始时间，毫秒", defaultValue = "1523894400000"),
            @ApiImplicitParam(paramType = "query", name = "endTime", dataType = "Long", required = true, value = "比赛结束时间，毫秒", defaultValue = "1524067200000"),
    })
    @ResponseBody
    public ResponseData subscribeEvent(Long beginTime, Long endTime) {

        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);


        Map<String, Object> map = new HashMap<>();

        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);
        map.put("language", SysConstant.LANGUAGE_TYPE);

        JSONArray array = GetResultUtils.getObject(SysConstant.EVENT_LIST, map).getBody().getJSONArray("data");

        for (int i = 0; i < array.size(); i++) {
            Long eventId = array.getJSONObject(i).getLong("eventId");
            Map<String, Object> bus = new HashMap<>();
            bus.put("eventId", eventId);
            bus.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);

            GetResultUtils.getObject(SysConstant.EVENT_SUBCRIBE, bus);
        }

        return data;
    }

    /**
     * 处理订单通知
     *
     * @param jsonObject
     */
    private void orderChangedNotificationHandle(JSONObject jsonObject) {
        JSONObject content = jsonObject.getJSONObject("content");
        JSONArray orders = content.getJSONArray("orders");

        for (int i = 0; i < orders.size(); i++) {
            JSONObject order = orders.getJSONObject(i);

            orderService.updateOrderStatus(order);
        }
    }

    /**
     * 市场状态改变通知
     *
     * @param jsonObject
     */
    private void marketChangedNotificationHandle(JSONObject jsonObject) {
        JSONObject content = jsonObject.getJSONObject("content");
        String eventId = content.getString("eventId");
        JSONArray markets = content.getJSONArray("markets");

        for (int i = 0; i < markets.size(); i++) {
            JSONObject market = markets.getJSONObject(i);
            Integer marketId = market.getInt("marketId");
            Integer state = market.getInt("state");

            if (state.equals(MarketState.MarketState_Closed.getStatus())) {

                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setMarketId(marketId);
                orderInfo.setOrderState(OrderStatus.Active.getValue());
                List<OrderInfo> list = orderService.selectByMarketId(orderInfo);

                System.out.println("MarketState_Closed" + marketId + " active order list: " + list.toString());

                if (list.size() > 0) {
                    //开启定时器，10分钟后拉取List的订单详情
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {

                            for (OrderInfo order : list) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("orderId", order.getTcmOrderId());
                                map.put("correlationOrderId", order.getOrderNumber());

                                TCMObject tcmObject = GetResultUtils.getObject(SysConstant.ORDER_INFO, map);
                                JSONObject orderJSON = tcmObject.getBody().getJSONObject("data");

                                orderService.updateOrderStatus(orderJSON);

                            }

                            this.cancel();
                        }
                    }, 1000 * 60 * 10);
                }
            }
        }
    }

    private JSONObject bodyFromRequest(HttpServletRequest request) {

        String str, jsonStr = "";

        try {
            BufferedReader br = null;

            br = request.getReader();

            while ((str = br.readLine()) != null) {
                jsonStr += str;
            }

        } catch (IOException e) {
            e.printStackTrace();
            jsonStr = "{}";
        }

        return JSONObject.fromObject(jsonStr);
    }
}
